package gameserver;

/** Used by Server. Contains a single connected client.
 *  This client acts as a player on the game board.
 *  The client also has built-in message handling communication with the Server **/

import java.net.Socket;
import java.io.DataInputStream;
import java.io.PrintStream;;


public class Connection extends Thread {
    public Socket clientSocket = null;
    public DataInputStream is = null; // stream for reading from client
    public PrintStream os = null; // stream for writing to client

    public int id = 0;
    public String name = "New Player";
    public Server server = null; // associated server

    // map coordinates
    public int x = 0;
    public int y = 0;

    /** Message handling method. **/
    public void start() {
        while (true) {
            try {
                String s;
                while ((s=is.readUTF()) != null) {
                        server.events.add(new Data(s, this)); // add any incoming messages to the queue
                }
            } catch (Exception e) {
                System.out.println("Unable to read from client.");
            }
        }
    }

    // constructors .........................................................

    // null connection = server side message
    public Connection(Server server, Socket clientSocket, String name, int id) {
        super("Connection");
        this.server = server;
        this.name = name;
        this.id = id;

        this.clientSocket = clientSocket;
        try {
            is = new DataInputStream(clientSocket.getInputStream());
            os = new PrintStream(clientSocket.getOutputStream());
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }

        start(); // start automatically
    }

    public Connection(Server server, Socket clientSocket, int id) {
        this(server, clientSocket, "New Player", id);
    }

    public Connection(Server server, Socket clientSocket) {
        this(server, clientSocket, "New Player", 0);
    }

    public Connection() {
        this(null, null, "New Player", 0);
    }
}
